﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using BySoft.Server.Business;
using BySoft.Web.Utility;
using BySoft.Server.Common.Entity;
using BySoft.Server.Common.Schema;
using BySoft.Server.Common;
using BySoft.Server.Consts;
using BySoft.Server.Common.Enum;
using OneSoft.EntityCore;

namespace BySoft.Web.Site.SysManage
{
    public partial class RoleAdd : AuthBasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindRights();
                CreateMemberTable();
                BindMember();
            }

        }

        protected void Page_Init(object sender, EventArgs e)
        {
            Master.ValidationGroup = "gSubmit";
        }

        private void BindRights()
        {
            DataTable dtRights = SysModule.GetSysModuleList();
            if (dtRights.Rows.Count > 0)
            {
                sgvRights.DataSource = dtRights;
                sgvRights.DataBind();
            }
            else
            {
                UIHelper.BindEmptyGridView(sgvRights, dtRights);
            }
        }

        private void CreateMemberTable()
        {
            DataTable dtMenber = new DataTable();
            dtMenber.Columns.Add("ID");
            dtMenber.Columns.Add("DISPLAY_ID");
            dtMenber.Columns.Add("NAME");
            dtMenber.AcceptChanges();

            DtMember = dtMenber;
        }

        private void BindMember()
        {
            if (DtMember.Rows.Count > 0)
            {
                sgvMember.DataSource = DtMember;
                sgvMember.DataBind();
            }
            else
            {
                UIHelper.BindEmptyGridView(sgvMember, DtMember);
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            DataTable dtRole = SysRole.GetRoleByRoleName(txtRoleName.Text);
            if (dtRole.Rows.Count > 0)
            {
                UIHelper.AlertMessage(this.Page, Message.RoleExist);
                return;
            }
            SysRoleEntity oSysRole = new SysRoleEntity();
            oSysRole.RoleName = txtRoleName.Text.Trim();
            oSysRole.Description = txtDesc.Text.Trim();
            oSysRole.Status = "1";
            oSysRole.CreateUserID = CurrentUser.UserID;
            oSysRole.CreateDate = DateTime.Now;
            oSysRole.ModifyUserID = CurrentUser.UserID;
            oSysRole.ModifyDate = DateTime.Now;

            List<SysRolerightsEntity> listSysRolerights = new List<SysRolerightsEntity>();
            List<SysUserroleEntity> listSysUserrole = new List<SysUserroleEntity>();


            //角色权限
            foreach (GridViewRow gvr in sgvRights.Rows)
            {
                if (sgvRights.DataKeys[gvr.RowIndex].Values[SysModuleTable.C_PAGETYPE].ToString().Equals("F"))
                {
                    string sTemp = "";
                    if (((CheckBox)gvr.FindControl("cbView")).Checked && ((CheckBox)gvr.FindControl("cbView")).Visible)
                    {
                        sTemp = "R";
                    }
                    if (((CheckBox)gvr.FindControl("cbAdd")).Checked && ((CheckBox)gvr.FindControl("cbAdd")).Visible)
                    {
                        sTemp += "C";
                    }
                    if (((CheckBox)gvr.FindControl("cbDel")).Checked && ((CheckBox)gvr.FindControl("cbDel")).Visible)
                    {
                        sTemp += "D";
                    }
                    if (((CheckBox)gvr.FindControl("cbUpdate")).Checked && ((CheckBox)gvr.FindControl("cbUpdate")).Visible)
                    {
                        sTemp += "U";
                    }
                    if (((CheckBox)gvr.FindControl("cbExport")).Checked && ((CheckBox)gvr.FindControl("cbExport")).Visible)
                    {
                        sTemp += "E";
                    }
                    if (((CheckBox)gvr.FindControl("cbApprove")).Checked && ((CheckBox)gvr.FindControl("cbApprove")).Visible)
                    {
                        sTemp += "A";
                    }
                    if (!sTemp.Equals(""))
                    {
                        SysRolerightsEntity oSysRolerights = new SysRolerightsEntity();
                        oSysRolerights.RoleID = oSysRole.RoleID;
                        oSysRolerights.RightsCode = sTemp;
                        oSysRolerights.ModulePrimaryID = Convert.ToInt32(sgvRights.DataKeys[gvr.RowIndex].Values["ModulePrimaryID"].ToString());
                        //oSysRolerights.Datarights = "";

                        listSysRolerights.Add(oSysRolerights);
                    }
                }
            }
            //角色成员
            foreach (GridViewRow gvr in sgvMember.Rows)
            {
                if (!String.IsNullOrEmpty(gvr.Cells[0].Text))
                {
                    //个人用户
                    SysUserroleEntity oSysUserrole = new SysUserroleEntity();
                    oSysUserrole.UserID = sgvMember.DataKeys[gvr.RowIndex].Values["ID"].ToString();
                    oSysUserrole.RoleID = oSysRole.RoleID;
                    listSysUserrole.Add(oSysUserrole);
                }
            }
            if (SysRole.AddRole(oSysRole, listSysRolerights, listSysUserrole))
            {
                DtMember = null;
                WriteLog(oSysRole, listSysRolerights, listSysUserrole, true);
                UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "/SysManage/RoleList.aspx");
            }
            else
            {
                WriteLog(oSysRole, listSysRolerights, listSysUserrole, false);
                UIHelper.AlertMessage(this.Page, Message.SaveFail);
            }
        }

        private void WriteLog(SysRoleEntity oSysRole, List<SysRolerightsEntity> listSysRolerights, List<SysUserroleEntity> listSysUserrole, bool isResult)
        {
            DataTable dt1 = CommonMethod.convert2Table(listSysRolerights);
            DataTable dt2 = CommonMethod.convert2Table(listSysUserrole);
            DataSet ds = new DataSet();
            ds.Tables.Add(dt1);
            ds.Tables.Add(dt2);

            oSysRole.SubDataSet = ds;

            base.LogAction(BaseEnum.ActionType.Add, oSysRole.RoleID.Value.ToString(), isResult, null, new EntityBase[] { oSysRole });

        }


        protected void sgvRights_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //add by liu
                //((CheckBox)e.Row.FindControl("cbApprove")).Visible = false;
                if (sgvRights.DataKeys[e.Row.RowIndex].Values[SysModuleTable.C_PAGETYPE].ToString().Equals("F"))
                {
                    if (!sgvRights.DataKeys[e.Row.RowIndex].Values[SysModuleTable.C_MODULERIGHTS].ToString().Contains("R"))
                    {
                        ((CheckBox)e.Row.FindControl("cbView")).Visible = false;
                    }
                    if (!sgvRights.DataKeys[e.Row.RowIndex].Values[SysModuleTable.C_MODULERIGHTS].ToString().Contains("C"))
                    {
                        ((CheckBox)e.Row.FindControl("cbAdd")).Visible = false;
                    }
                    if (!sgvRights.DataKeys[e.Row.RowIndex].Values[SysModuleTable.C_MODULERIGHTS].ToString().Contains("D"))
                    {
                        ((CheckBox)e.Row.FindControl("cbDel")).Visible = false;
                    }
                    if (!sgvRights.DataKeys[e.Row.RowIndex].Values[SysModuleTable.C_MODULERIGHTS].ToString().Contains("U"))
                    {
                        ((CheckBox)e.Row.FindControl("cbUpdate")).Visible = false;
                    }
                    if (!sgvRights.DataKeys[e.Row.RowIndex].Values[SysModuleTable.C_MODULERIGHTS].ToString().Contains("E"))
                    {
                        ((CheckBox)e.Row.FindControl("cbExport")).Visible = false;
                    }
                    if (!sgvRights.DataKeys[e.Row.RowIndex].Values[SysModuleTable.C_MODULERIGHTS].ToString().Contains("A"))
                    {
                        ((CheckBox)e.Row.FindControl("cbApprove")).Visible = false;
                    }
                }
                else
                {
                    ((CheckBox)e.Row.FindControl("cbRowAll")).Visible = false;
                    ((CheckBox)e.Row.FindControl("cbView")).Visible = false;
                    ((CheckBox)e.Row.FindControl("cbAdd")).Visible = false;
                    ((CheckBox)e.Row.FindControl("cbDel")).Visible = false;
                    ((CheckBox)e.Row.FindControl("cbUpdate")).Visible = false;
                    ((CheckBox)e.Row.FindControl("cbExport")).Visible = false;
                    ((CheckBox)e.Row.FindControl("cbApprove")).Visible = false;
                }
            }
        }

        protected DataTable DtMember
        {
            get
            {
                if (Session["RoleAdd_DtMember"] != null)
                {
                    return (DataTable)Session["RoleAdd_DtMember"];
                }
                else
                {
                    return null;
                }
            }
            set
            {
                Session["RoleAdd_DtMember"] = value;
            }
        }

        protected void sgvMember_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "del")
            {
                for (int i = 0; i < DtMember.Rows.Count; i++)
                {
                    if (DtMember.Rows[i]["ID"].ToString() == e.CommandArgument.ToString())
                    {
                        DtMember.Rows.RemoveAt(i);
                        break;
                    }
                }
                BindMember();
                //ClientScript.RegisterStartupScript(this.GetType(), "", "<script>showtab(2)</script>");
            }
        }

        protected void sgvMember_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton ibtn = (ImageButton)e.Row.FindControl("ibtnDel");
                Button btnDel = (Button)e.Row.FindControl("btnDel");
                if (ibtn != null)
                {
                    ibtn.OnClientClick = "ShowTopConfirm('提示信息','您正在删除成员：" + e.Row.Cells[1].Text + "，您确认继续吗？','confirmCallback(\\'" + btnDel.ClientID + "\\')');return false;";
                }
            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (Session["RoleMember_Member"] != null)
            {
                if (DtMember.Rows[0][0].ToString().Equals(""))
                {
                    DtMember.Rows.RemoveAt(0);
                    DtMember.AcceptChanges();
                }

                DataTable dtNew = (DataTable)Session["RoleMember_Member"];
                for (int i = 0; i < dtNew.Rows.Count; i++)
                {
                    if (DtMember.Select("ID='" + dtNew.Rows[i]["ID"].ToString() + "'").Length == 0)
                    {
                        for (int j = 0; j < dtNew.Columns.Count; j++)
                        {
                            if (dtNew.Rows[i][j].ToString().Equals("&nbsp;"))
                            {
                                dtNew.Rows[i][j] = "";
                            }
                        }
                        DtMember.ImportRow(dtNew.Rows[i]);
                    }
                }
                DtMember.AcceptChanges();
                BindMember();
                Session["RoleMember_Member"] = null;
            }
            ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "", "<script>iframeAutoFit();</script>", false);
        }

        public string GetModuleName(object moduleName)
        {
            if (!moduleName.ToString().StartsWith(" "))//一级菜单粗体
            {
                moduleName = "<B>" + moduleName + "</B>";
            }
            return moduleName.ToString().Replace(" ", "&nbsp;");
        }
    }
}
